package com.wkbb.sports.websocket;

import com.wkbb.sports.service.WorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author lbh
 * @date 2021年04月25日 14:40:29
 * @description: 在项目启动时对相关资源进行触发初始化和在项目关闭时对相关资源进行释放的监听器
 */
@WebListener
@Component
public class JobListener implements ServletContextListener {

    @Autowired
    private WorkService workService;

    /**
     * 定时改变作业状态
     */
    private static ScheduledExecutorService sensorService;
    private static ScheduledFuture sensorFuture = null;


    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //System.out.println("=========定时改变作业状态====监听器被触发==");
        scheduleUpdateWorkStatus();
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //System.out.println("=======================Shutting down 定时改变作业状态监听器=======");
        close();
    }

    /**
     * 定时改变作业状态，然后每隔1分钟一次
     */
    public void scheduleUpdateWorkStatus(){
        sensorService = Executors.newSingleThreadScheduledExecutor();
        sensorFuture = sensorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                //System.out.println("=========定时改变作业状态====监听器被触发==");
                workService.updateWorkStatus();
            }
        },  0,1, TimeUnit.MINUTES);
    }

    public void close(){
        if(sensorService != null){
            //System.out.println("=======================Shutting down 定时改变作业状态监听器=======");
            sensorService.shutdownNow();
            sensorService = null;
        }
    }
}
